package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {



    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }


    /***
     *
     * 机构认证申请
     * @param dto
     */
    @Override
    public void application(AgencyCertificationAuditResDTO dto) {
        //直接构建对象，将它添加到数据库中
        AgencyCertification certification = BeanUtils.copyBean(dto, AgencyCertification.class);
    }


    /**
     * 运营端-机构认证信息审核
     * @param dto
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> getPage(AgencyCertificationAuditPageQueryReqDTO dto) {
        Page<AgencyCertification> pageQuery = PageUtils.parsePageQuery(dto, AgencyCertification.class);
        Page<AgencyCertification> page = this.lambdaQuery()
                .eq(dto.getAuditStatus() != null, AgencyCertification::getAuditStatus, dto.getAuditStatus())
                .eq(dto.getCertificationStatus() != null, AgencyCertification::getCertificationStatus,
                        dto.getCertificationStatus())
                .like(StringUtils.isNotBlank(dto.getLegalPersonName()), AgencyCertification::getLegalPersonName, dto.getLegalPersonName())
                .like(dto.getName() != null, AgencyCertification::getName, dto.getName())
                .orderBy(!dto.getIsAsc1(), dto.getIsAsc1(), AgencyCertification::getCreateTime)
                .page(pageQuery);
        PageResult<AgencyCertificationAuditResDTO> pageResult = PageUtils.toPage(page, AgencyCertificationAuditResDTO.class);
        return pageResult;
    }


    /**
     * 审核机构认证信息
     * @param id
     * @param certificationStatus
     * @param rejectReason
     */
    @Override
    public void auditAgencyInfo(Long id, Long certificationStatus, String rejectReason) {
        //判断当前用户是否存在
        AgencyCertification agencyCertification = this.lambdaQuery()
                .eq(AgencyCertification::getId, id)
                .one();
        if (agencyCertification == null){
            throw new ForbiddenOperationException("不存在");
        }
        //获取当前用户的名称
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        String name = currentUserInfo.getName();
        //更改当前用户的状态
        boolean result = this.lambdaUpdate().eq(AgencyCertification::getId, id)
                .set(AgencyCertification::getAuditStatus, AuditStatusEnum.AUDITED.getStatus())
                .set(AgencyCertification::getCertificationStatus, certificationStatus)
                .set(AgencyCertification::getAuditorId, UserContext.currentUserId())
                .set(AgencyCertification::getAuditTime, LocalDateTime.now())
                .set(StringUtils.isNotBlank(rejectReason), AgencyCertification::getRejectReason, rejectReason)
                .set(AgencyCertification::getAuditorName, name)
                .update();
        if (!result){
            throw new DBException("数据库异常");
        }
    }

@Autowired
private IServeProviderService serveProviderService;

    /**
     * 机构端提交让认证申请
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certificationApplication(AgencyCertificationAuditAddReqDTO dto) {
        //这里的id存储id是服务提供者的id
        AgencyCertification agencyCertification = BeanUtils.copyBean(dto, AgencyCertification.class);
        agencyCertification.setId(UserContext.currentUserId());
        agencyCertification.setServeProviderId(UserContext.currentUserId());
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setCertificationTime(LocalDateTime.now());
        boolean result = this.save(agencyCertification);
        if (!result){
            throw new DBException("保存认证申请失败");
        }
        //成功之后，将服务提供者的状态更改掉
        boolean result1 = serveProviderService.lambdaUpdate()
                .eq(ServeProvider::getId, dto.getServeProviderId())
                .set(ServeProvider::getSettingsStatus,
                        CertificationStatusEnum.PROGRESSING.getStatus())
                .update();
    }


    /**
     * 查询最新的拒绝原因
     * @return
     */
    @Override
    public RejectReasonResDTO getJectReason() {
        //判断当前用户是否有驳回原因
        //获取当前用户
        Long id = UserContext.currentUserId();
        AgencyCertification agencyCertification = this.lambdaQuery()
                .eq(AgencyCertification::getId, id).one();
        if (agencyCertification == null){
            return null;
        }
        //如果不为空，就将原因返回
        String rejectReason = agencyCertification.getRejectReason();
        RejectReasonResDTO reasonResDTO = RejectReasonResDTO.builder()
                .rejectReason(rejectReason)
                .build();
        return reasonResDTO;
    }
}
